#! /bin/sh
### BEGIN INIT INFO
# Provides:          ap6212-bluetooth
# Required-Start:    $local_fs
# Required-Stop:
# X-Start-Before:    bluetooth
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Patch firmware for ap6212 adapter
# Description:       Patch firmware for ap6212 adapter
### END INIT INFO

DEFAULTS="/etc/default/ap6212"

# Include ap6212 defaults if available
if [ -r "${DEFAULTS}" ]
then
	. "${DEFAULTS}"
fi

# exit if bluetooth utils are not installed
[ -f "/bin/hciconfig" ] || exit 0

# copy firmware

if [ -f "/lib/firmware/ap6212/bcm43438a0.hcd" ] && [ ! -f /etc/firmware/ap6212/4343A0.hcd ]; then
        mkdir -p /etc/firmware/ap6212
        cp /lib/firmware/ap6212/bcm43438a0.hcd /etc/firmware/ap6212/4343A0.hcd
fi


if [ -f "/lib/firmware/ap6212/bcm43438a1.hcd" ] && [ ! -f /etc/firmware/ap6212/BCM43430A1.hcd ]; then
        mkdir -p /etc/firmware/ap6212
        cp /lib/firmware/ap6212/bcm43438a1.hcd /etc/firmware/ap6212/BCM43430A1.hcd
fi

. /lib/lsb/init-functions

do_start () {

if [ ! -z $(hciconfig | /bin/grep UART | /usr/bin/cut -d: -f1) ]
then
    echo "ap6212 BT device allready initialized"
    hcitool dev
 else
	# Select MAC address
    if [ -z "$MAC_ADDR" ]; then       
       MAC_OPTIONS="11:22:33:44:55:66"
    else
       MAC_OPTIONS="$MAC_ADDR"
    fi
    # Select tty port
    if [ -z "$PORT" ]; then
       log_warning_msg "No PORT set in /etc/default/ap6212, will use ttyS1"
       PORT="ttyS1"
    fi
    
	# Start patching
        rfkill unblock all
        echo "0" > /sys/class/rfkill/rfkill0/state
        echo "1" > /sys/class/rfkill/rfkill0/state
        #on orangepi win following command never ends on first try... force to run with a timeout...
        timeout 5s echo " " > /dev/$PORT
        if [ $? != 0 ]; then
                #timed out... retry
                echo " " > /dev/$PORT
        fi
        hciattach /dev/$PORT bcm43xx 115200 flow bdaddr $MAC_OPTIONS
        hciconfig hci0 up
fi
}

case "$1" in
  start)
        do_start
        ;;
  restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
  stop)
        # No-op
        ;;
  status)
        hcitool dev
        ;;
  *)
        echo "Usage: ap6212-bluetooth [start|stop|status]" >&2
        exit 3
        ;;
esac